using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using UwinEducation.Domain.Entities;
using UwinEducation.Domain.IRepositories;
using UwinEducation.Infrastructure.Persistence;
using UwinEducation.Shared.Enums;
using UwinEducation.Shared.Models;

namespace UwinEducation.Infrastructure.Repositories
{
    /// <summary>
    /// 订单支付仓储实现
    /// </summary>
    public class OrderPaymentRepository : Repository<OrderPayment, Guid>, IOrderPaymentRepository
    {
        private readonly ApplicationDbContext _context;
        private readonly DbSet<OrderPayment> _dbSet;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public OrderPaymentRepository(ApplicationDbContext context) : base(context)
        {
            _context = context;
            _dbSet = context.Set<OrderPayment>();
        }

        /// <summary>
        /// 根据订单ID获取支付记录列表
        /// </summary>
        /// <param name="orderId">订单ID</param>
        /// <returns>支付记录列表</returns>
        public async Task<List<OrderPayment>> GetByOrderIdAsync(Guid orderId)
        {
            return await _dbSet
                .Where(p => p.OrderId == orderId)
                .Include(p => p.Order) // 可选，如果需要显示订单信息
                .OrderByDescending(p => p.PaymentTime)
                .ToListAsync();
        }

        /// <summary>
        /// 分页获取订单支付记录
        /// </summary>
        /// <param name="request">分页请求参数</param>
        /// <returns>分页结果</returns>
        public async Task<PagedResult<OrderPayment>> GetPagedAsync(OrderPaymentPageRequest request)
        {
            var query = _dbSet.Include(p => p.Order)
                .Include(p => p.Creator)
                .Include(p => p.Auditor)
                .Include(p => p.Student)
                .AsNoTracking() // 添加 AsNoTracking 提升查询性能
                .AsSplitQuery() // 使用分割查询避免笛卡尔积
                .AsQueryable();

            // 订单ID筛选
            if (request.OrderId.HasValue)
            {
                query = query.Where(p => p.OrderId == request.OrderId.Value);
            }

            // 支付方式筛选
            if (request.PaymentMethod.HasValue)
            {
                query = query.Where(p => p.PaymentMethod == request.PaymentMethod.Value);
            }
            if (request.AuditStatus.HasValue)
            {
                query = query.Where(p => p.AuditStatus == request.AuditStatus.Value);
            }

            // 日期范围筛选
            if (request.StartDate.HasValue)
            {
                query = query.Where(p => p.PaymentTime >= request.StartDate.Value);
            }
            if (request.EndDate.HasValue)
            {
                query = query.Where(p => p.PaymentTime <= request.EndDate.Value);
            }

            //// 关键词搜索 (订单号, 凭证号, 备注)
            //if (!string.IsNullOrEmpty(request.SearchTerm))
            //{
            //    query = query.Where(p =>
            //        (p.Order != null && p.Order.OrderNumber.Contains(request.SearchTerm)) ||
            //        (!string.IsNullOrEmpty(p.TransactionId) && p.TransactionId.Contains(request.SearchTerm)) ||
            //        (!string.IsNullOrEmpty(p.Remarks) && p.Remarks.Contains(request.SearchTerm)));
            //}

            // 计算总数
            var total = await query.CountAsync();

            // 分页和排序
            var items = await query
                .OrderByDescending(p => p.PaymentTime)
                .Skip((request.PageIndex - 1) * request.PageSize)
                .Take(request.PageSize)
                .ToListAsync();

            return new PagedResult<OrderPayment>
            {
                Items = items,
                Total = total
            };
        }

        /// <summary>
        /// 批量添加支付记录
        /// </summary>
        /// <param name="payments">支付记录列表</param>
        public async Task AddRangeAsync(List<OrderPayment> payments)
        {
            await _dbSet.AddRangeAsync(payments);
            await _context.SaveChangesAsync(); // 通常由服务层统一保存
        }

        /// <summary>
        /// 批量更新支付记录
        /// </summary>
        /// <param name="payments">支付记录列表</param>
        public async Task UpdateRangeAsync(List<OrderPayment> payments)
        {
            _dbSet.UpdateRange(payments);
            await _context.SaveChangesAsync(); // 通常由服务层统一保存
            await Task.CompletedTask; // 避免警告
        }

        /// <summary>
        /// 批量删除支付记录
        /// </summary>
        /// <param name="payments">支付记录列表</param>
        public async Task DeleteRangeAsync(List<OrderPayment> payments)
        {
            _dbSet.RemoveRange(payments);
            await _context.SaveChangesAsync(); // 通常由服务层统一保存
            await Task.CompletedTask; // 避免警告
        }

        /// <summary>
        /// 计算订单的总支付金额
        /// </summary>
        /// <param name="orderId">订单ID</param>
        /// <returns>总支付金额</returns>
        public async Task<decimal> GetTotalPaidAmountAsync(Guid orderId)
        {
            return await _dbSet
                .Where(p => p.OrderId == orderId)
                .SumAsync(p => p.Amount);
        }

        /// <summary>
        /// 根据ID获取支付记录，并包含订单信息
        /// </summary>
        /// <param name="id">支付ID</param>
        /// <returns>支付记录</returns>
        public override async Task<OrderPayment> GetByIdAsync(Guid id)
        {
            return await _dbSet
                .Include(p => p.Order)
                .FirstOrDefaultAsync(p => p.Id == id);
        }
    }
}